package com.whcoding.test.common;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @program: spring-boot-learning
 * @description: 原生bean转为map
 * @author: whcoding
 * @create: 2022-02-15 11:45
 **/
public class BeanConverOldUtil {

	/**
	 * 把JavaBean转化为map
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> bean2map(Object bean) {
		return bean2map(bean,true);
	}
	/**
	 * 把JavaBean转化为map
	 * ormUserPO 转为Map
	 * @param bean
	 * @param isSaveNull
	 * @return
	 */
	public static Map<String, Object> bean2map(Object bean, Boolean isSaveNull) {
		if (bean == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<>(16);
		try {
			//获取JavaBean的描述器
			BeanInfo b = Introspector.getBeanInfo(bean.getClass(), Object.class);
			//获取属性描述器
			PropertyDescriptor[] pds = b.getPropertyDescriptors();
			//对属性迭代
			if (pds==null||pds.length==0){
				return null;
			}
			for (PropertyDescriptor pd : pds) {
				//属性名称
				String propertyName = pd.getName();
				if (!propertyName.equals("class")) {
					//属性值,用getter方法获取
					Method m = pd.getReadMethod();
					//用对象执行getter方法获得属性值
					Object properValue = m.invoke(bean);
					//把属性名-属性值 存到Map中
					if (isSaveNull) {
						map.put(propertyName, properValue);
					} else {
						if (Objects.nonNull(properValue)) {
							map.put(propertyName, properValue);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}



}

